<?php

namespace App\Kuafu\CustomerCoupon\Controller\Applet;

use App\Exceptions\BaseException;
use App\Kuafu\Activity\Enum\ActivityCodeEnum;
use App\Kuafu\Activity\Enum\ActivityEnum;
use App\Kuafu\Activity\Service\ActivityService;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Customer\Enum\CustomerCodeEnum;
use App\Kuafu\Customer\Enum\PlatformCodeEnum;
use App\Kuafu\Customer\Service\CustomerPlatformService;
use App\Kuafu\Customer\Service\CustomerSendCouponLogService;
use App\Kuafu\CustomerCoupon\Enum\CodeEnum;
use App\Kuafu\CustomerCoupon\Enum\CustomerCouponCacheEnum;
use App\Kuafu\CustomerCoupon\Enum\CustomerCouponCodeEnum;
use App\Kuafu\CustomerCoupon\Exceptions\CustomerCouponException;
use App\Kuafu\CustomerCoupon\Model\CustomerCouponModel;
use App\Kuafu\CustomerCoupon\Service\CustomerCouponService;
use App\Kuafu\CustomerCoupon\Validate\CustomerCouponNewValidate;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Service\DouyinSelfLibrary\DouyinSelfService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Service\AuthService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Validation\ValidationException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\InvalidArgumentException;

class CustomerCouponController extends BaseController
{
    public function getUserCouponList(Request $request)
    {
        $status     = $request->status ?: 0;
        $pageNum    = (int)$request->get('pageNum', 1);
        $pageSize   = (int)$request->get('pageSize', 20);
        $poiId      = (string)$request->get('poiId', '');
        $platformId = (int)$request->header('platformId', 1);
        $openId     = (string)$request->header('openId', '');
        $couponType      = (int)$request->get('couponType', 0); // 类型
        $availableSource = (int)$request->get('availableSource', 0); // 渠道
        $bodyShopId      = (int)$request->get('shopId', 0); // 注意此处的shopId，优先使用
        $headerShopId    = (int)$request->header('shopId', 0);
        $isGetNowCoupon  = (int)$request->get('isGetNowCoupon', 0); // 是否获取当前有效的优惠券

        $searchShopId = $bodyShopId; // 用作搜索

        // 不传默认使用header
        if ($bodyShopId == 0){
            $bodyShopId = $headerShopId;
        }


        // 抖音小程序
        if ($platformId == PlatformCodeEnum::PLATFORM_APPLET_DOUYIN) {
            $userCouponList = CustomerCouponService::getUserCouponListFromDy($openId, $poiId, $pageNum, $pageSize);
            if (!$userCouponList) {
                $data = [
                    'pageNum'  => 1,
                    'pageSize' => 20,
                    'count'    => 0,
                    'list'     => []
                ];
                return $this->success($data);
            }
        } else {
            // 店铺信息
            $shop = ShopService::getShopInfo($bodyShopId);
            if (!$shop) {
                return $this->fail(CustomerCouponCodeEnum::ERR_CUSTOMERCOUPON_PARAM_VALID);
            }
            $brandId = 1;

            $userId = CustomerPlatformService::getUserId($request);
            if (!$userId) {
                $data = [
                    'pageNum'  => 1,
                    'pageSize' => 20,
                    'count'    => 0,
                    'list'     => []
                ];
                return $this->success($data);
            }
            $userCouponList = CustomerCouponService::getUserCouponList($userId, $status, $pageNum, $pageSize, $couponType, $availableSource, $bodyShopId, $searchShopId, $brandId, $isGetNowCoupon);
        }
        return $this->success($userCouponList);
    }

    /**
     * 获取用户可用优惠券列表
     * @param Request $request
     */
    public function getUserCanUseCouponList(Request $request)
    {
        $brandId                     = 1;
        $shopId                      = 1;
        $userId                      = 1;
        $productList                 = [
            ['productId' => 385, 'number' => 1000, 'price' => 1000]
        ];
        $usedCouponList              = [
//            [
//                'couponCode' => '82801182404370'
//            ],
//            [
//                'couponCode' => 37175186615097
//            ],
//            [
//                'couponCode'   => '07911356060621',
//            ]
        ];
        $Source                      = \App\Kuafu\Order\Enum\CodeEnum::SOURCE_TYPE_MINI;
        $customerEnableCouponService = CustomerCouponService::getUserCanUseCouponList($brandId, $shopId, $userId,
            $productList, $usedCouponList,
            $Source);
        $can                         = $customerEnableCouponService->getCanUseCouponList();
        $no                          = $customerEnableCouponService->getCanNotUseCouponList();
        return $this->success(['can' => $can, 'no' => $no]);
    }


    /**
     * 用户绑定手机号发放优惠券
     * @throws CustomerCouponException
     */
    public function bandMobileSendCoupon(Request $request): JsonResponse
    {
        $userId = CustomerPlatformService::getUserId($request);
        $shopId = $this->shopId;
        //加锁
        $lockKey = CustomerCouponCacheEnum::getSendCouponLock($userId);
        if (!Redis::setnx($lockKey, time())) {
            // 防止死锁
            $lock_time = Redis::get($lockKey);
            if (($lock_time + 5) < time()) {
                Redis::del($lockKey);
            } else {
                return $this->fail(CodeEnum::ERR_400000, '您的请求太频繁啦，请稍后再试~');
            }
        }
        $activityType = ActivityEnum::TYPE_REGISTRATION;
        //判断用户是否领取过注册有礼活动优惠券
        $isSend = CustomerSendCouponLogService::checkIsSend($userId, $activityType);
        if ($isSend) {
            return $this->fail(CustomerCodeEnum::ERR_CUSTOMER_ALREADY_RECEIVED,
                CustomerCodeEnum::CODE_TEXT[CustomerCodeEnum::ERR_CUSTOMER_ALREADY_RECEIVED]);
        }
        //根据店铺id获取活动id
        $activityId = ActivityService::getActivityIdByShopInfo($activityType, $shopId);
        if ($activityId) {
            //触发领券
            CustomerCouponService::sendCoupon($userId, $activityId, $activityType, $shopId);
            //删除用户缓存
            Redis::del(\App\Kuafu\Customer\Enum\CodeEnum::PREFIX_PLATFORM . $request->header('platformId') . ':' . \App\Kuafu\Customer\Enum\CodeEnum::PREFIX_USERID . $userId);

            Redis::del($lockKey);

            return $this->success();
        } else {

            Redis::del($lockKey);

            return $this->fail(ActivityCodeEnum::ERR_ACTIVITY_NO_EXIST,
                ActivityCodeEnum::CODE_TEXT[ActivityCodeEnum::ERR_ACTIVITY_NO_EXIST]);
        }
    }

    /**
     * @throws CustomerCouponException
     */
    public function buyCouponPackageSendCoupon(Request $request)
    {
        $packageId  = $request->packageId;
        $userId     = $request->userId;
        $type       = ActivityEnum::TYPE_COUPON_PACKAGE;
        $usedCoupon = [177 => 1];
        //获取券包详情
        CustomerCouponService::buyCouponPackageSendCoupon($packageId, $userId, $type, $usedCoupon, $this->shopId);

    }


    /**
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|CustomerCouponException
     */
    public function customerCouponDetail(Request $request, $id): JsonResponse
    {
        CustomerCouponNewValidate::customerCouponDetailValidate($request->merge(["id" => $id])->all());
        return $this->success(CustomerCouponService::customerCouponDetail($id));
    }

    /**
     * 校验优惠券状态
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     */
    public function checkCouponStatus(Request $request, $id): JsonResponse
    {
        CustomerCouponNewValidate::customerCouponDetailValidate($request->merge(["id" => $id])->all());
        return $this->success([
            'couponStatus' => CustomerCouponService::checkCouponStatus($id, $request->user()->userId)
        ]);
    }

    /**
     * 活动领券
     *
     * @param Request $request
     * @param int $activityId
     * @return JsonResponse
     * @throws BaseException
     * @throws CustomerCouponException|InvalidArgumentException
     */
    public function activityReceiveCoupon(Request $request, $activityId): JsonResponse
    {
        return $this->success(CustomerCouponService::activityCouponReceive(
            $request->user()->userId,
            $this->shopId,
            $activityId,
            $request->header('platformId')
        ));
    }
}
